<template>
  <div class="inbound-orders-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">入库管理</h1>
      </div>
      <div class="header-actions">
        <el-alert
          title="提示：如需进行入库单数据维护（新增/编辑/删除/导入/导出），请使用数据管理模式"
          type="info"
          show-icon
          closable
          class="data-management-tip"
        />
      </div>
    </div>

    <!-- 统计概览 -->
    <InboundStats :stats="stats" />
    
    <!-- 筛选条件 -->
    <InboundFilter 
      :suppliers="suppliers"
      :query-params="queryParams"
      @search="handleSearch"
      @reset="handleReset"
    />
    
    <!-- 入库单列表 -->
    <InboundTable
      :table-data="tableData"
      :loading="loading"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
      @page-change="handlePageChange"
      @detail="showDetail"
    />
    
    <!-- 入库单详情抽屉 -->
    <InboundDetail
      v-model:model-value="detailDrawerVisible"
      :inbound-order="selectedInboundOrder"
      @close="detailDrawerVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { 
  Document, Money, Warning, Plus, Upload, Download, Refresh
} from '@element-plus/icons-vue'
// import { formatCurrency } from '@/utils/formatters'

// API导入
import * as procurementAPI from '@/api/procurement'

// 组件导入
import InboundStats from '@/components/procurement/InboundStats.vue'
import InboundFilter from '@/components/procurement/InboundFilter.vue'
import InboundTable from '@/components/procurement/InboundTable.vue'
import InboundDetail from '@/components/procurement/InboundDetail.vue'

// 数据模型
interface InboundOrderItem {
  id: number
  productName: string
  specification: string
  quantity: number
  unitPrice: number
}

interface InboundOrder {
  id: number
  inboundNumber: string
  supplierId: number
  supplierName: string
  inboundDate: string
  totalAmount: number
  hasInvoice: boolean
  invoiceStatus: string
  freight: number
  remark: string
  items: InboundOrderItem[]
}

interface Stats {
  monthlyInboundAmount: number
  monthlyInboundCount: number
  pendingInvoiceCount: number
  supplierCount: number
  amountTrend: number
  countTrend: number
  invoiceTrend: number
  supplierTrend: number
}

interface QueryParams {
  page: number
  limit: number
  inboundNumber: string
  supplierId: number | null
  invoiceStatus: string
  inboundDateRange: string[]
  sortField: string
  sortOrder: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const suppliers = ref<procurementAPI.Supplier[]>([])

const tableData = ref<InboundOrder[]>([])
const loading = ref(false)

const detailDrawerVisible = ref(false)
const selectedInboundOrder = ref<InboundOrder | null>(null)

// 统计信息
const stats = reactive<Stats>({
  monthlyInboundAmount: 0,
  monthlyInboundCount: 0,
  pendingInvoiceCount: 0,
  supplierCount: 0,
  amountTrend: 0,
  countTrend: 0,
  invoiceTrend: 0,
  supplierTrend: 0
})

// 查询参数
const queryParams = reactive<QueryParams>({
  page: 1,
  limit: 20,
  inboundNumber: '',
  supplierId: null,
  invoiceStatus: '',
  inboundDateRange: [],
  sortField: 'inbound_date',
  sortOrder: 'desc'
})

// 分页信息
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 方法
const loadInboundOrders = async () => {
  loading.value = true
  try {
    const response = await procurementAPI.getInboundOrders(queryParams)
    tableData.value = response.data.list
    pagination.total = response.data.pagination.total
    pagination.currentPage = response.data.pagination.page
    pagination.pageSize = response.data.pagination.limit
    ElNotification({
      title: '加载完成',
      message: `成功加载 ${response.data.list.length} 条入库单记录`,
      type: 'success',
      duration: 2000
    })
  } catch (error) {
    ElMessage.error('加载入库单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  loadInboundOrders()
}

const handleReset = () => {
  Object.assign(queryParams, {
    inboundNumber: '',
    supplierId: null,
    invoiceStatus: '',
    inboundDateRange: [],
    sortField: 'inbound_date',
    sortOrder: 'desc',
    page: 1,
    limit: 20
  })
  loadInboundOrders()
}

const handlePageChange = (newPage: number) => {
  queryParams.page = newPage
  loadInboundOrders()
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  ElMessage.info(`按 ${sort.prop} ${sort.order} 排序`)
}

const handleSelectionChange = (selection: InboundOrder[]) => {
  // 入库管理中不需要处理选择
}

const handleRowClick = (row: InboundOrder) => {
  showDetail(row)
}

const showDetail = (order: InboundOrder) => {
  selectedInboundOrder.value = order
  detailDrawerVisible.value = true
}

// 生命周期钩子
onMounted(() => {
  loadInboundOrders()
})
</script>